<?php
class PostsController extends AppController {

	var $name = 'Posts';
	var $helpers = array('Ajax', 'Javascript', 'Yelp', 'GoogleMapV3');
	var $components = array('Uploader');

	function index($user_id=null) {
		$this->Post->recursive = 2;
		if($user_id==null){
			$this->set('posts', $this->Post->find("all"));
			$this->set('lastTen', $this->Post->find("all", array('order' =>'Post.created DESC','limit' => 10 )));
			$this->set('watching',"All Pictures");
		}else{
			App::import('Helper', 'Facebook');
       		$fb = new FacebookHelper();
			$this->set('posts', $this->Post->find("all",array("conditions"=>array("fb_user_id"=>$user_id))));
			$this->set('lastTen', $this->Post->find("all", array("conditions"=>array("fb_user_id"=>$user_id),'order' =>'Post.created DESC','limit' => 10 )));
			$this->set('watching',$fb->get_name_from_id($user_id)." Pictures");
		}
	}
	
	function copyFile($url,$filename){
	$file = fopen ($url, "rb");
	if (!$file) return false; else {
		$fc = fopen($filename, "wb");
		while (!feof ($file)) {
			$line = fread ($file, 1028);
			fwrite($fc,$line);
		}
		fclose($fc);
		return true;
		}
	}
	

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(sprintf(__('Invalid %s', true), 'post'));
			$this->redirect(array('action' => 'index'));
		}
		$this->Post->recursive = 2;
		$this->set('post', $this->Post->read(null, $id));
	}

	function add() {
		if (!empty($this->data)) {
			$this->Post->create();
			if(!isset($this->data["Post"]["facebook"])){
			
			if($this->data['Image']['file']['size']>2097152){
				$this->Session->setFlash(sprintf(__('The %s could not be bigger than 2MB.', true), 'image'));
				return false;
			} }
			if ($post=$this->Post->save($this->data)) {
				//We get the coordinates with the address and we save a new point
				if (!empty($post)) {
					$this->data['Point']['post_id'] = $this->Post->id;
					App::import('Vendor', 'google_geo');
            		$googleGeo = new GoogleGeo($this->data["Post"]["address"]);
            		$geo = $googleGeo->geo();
            		$this->data['Point'] = array_merge($this->data['Point'],$geo); 
					$point=$this->Post->Point->save($this->data);
				}
				
				//We save a new picture that belongs to this post
				if(!isset($this->data["Post"]["facebook"])) {
				if (!empty($post)) {	
					
					$result = $this->Uploader->uploadFiles('images', $this->data['Image']); 
					if(array_key_exists('urls', $result)) {  
						$this->data['Image']['name']= str_replace(' ', '_',  $this->data['Image']['file']['name']);
					    $this->data['Image']['path'] = $result['urls'][0];
					    $this->data['Image']['post_id']= $this->Post->id;
					    $image=$this->Post->Image->save($this->data);
					    
					    //And create the thumbnail for the GoogleMap
					    if (!empty($image)) {	
							App::import('Vendor', 'thumb', array('file' => 'phpthumb'.DS.'ThumbLib.inc.php'));
							$thumb = PhpThumbFactory::create(IMAGES. $this->data['Image']['path']);
							$thumb->adaptiveResize(40, 40);
							$thumb->save(IMAGES."thumbnails/small_".$this->data['Image']['name']);
							$this->data['Thumbnail']['name_small']= "small_".$this->data['Image']['name'];
						    $this->data['Thumbnail']['path_small'] = "thumbnails/small_".$this->data['Image']['name'];
						    
						    $thumb = PhpThumbFactory::create(IMAGES. $this->data['Image']['path']);
							$thumb->adaptiveResize(200, 200);
							$thumb->save(IMAGES."thumbnails/big_".$this->data['Image']['name']);
							$this->data['Thumbnail']['name_big']= "big_".$this->data['Image']['name'];
						    $this->data['Thumbnail']['path_big'] = "thumbnails/big_".$this->data['Image']['name'];
						    
						    $this->data['Thumbnail']['image_id']=  $this->Post->Image->id;	
						    $this->Post->Image->Thumbnail->save($this->data);
					    }
					} 
				}
				}
				
				if(isset($this->data["Post"]["facebook"])) {
				if (!empty($post)) {	
					
					$result = $this->copyFile($this->data['Post']['facebook'], 'testname.jpg');
					echo $result;
					
						$this->data['Image']['name']= "testname.jpg";
					    $this->data['Image']['path'] = $this->data['Post']['facebook'];
					    $this->data['Image']['post_id']= $this->Post->id;
					    $image=$this->Post->Image->save($this->data);
					    
					    //And create the thumbnail for the GoogleMap
					    if (!empty($image)) {	
							App::import('Vendor', 'thumb', array('file' => 'phpthumb'.DS.'ThumbLib.inc.php'));
							$thumb = PhpThumbFactory::create(IMAGES. $this->data['Image']['path']);
							$thumb->adaptiveResize(40, 40);
							$thumb->save(IMAGES."thumbnails/small_".$this->data['Image']['name']);
							$this->data['Thumbnail']['name_small']= "small_".$this->data['Image']['name'];
						    $this->data['Thumbnail']['path_small'] = "thumbnails/small_".$this->data['Image']['name'];
						    
						    $thumb = PhpThumbFactory::create(IMAGES. $this->data['Image']['path']);
							$thumb->adaptiveResize(200, 200);
							$thumb->save(IMAGES."thumbnails/big_".$this->data['Image']['name']);
							$this->data['Thumbnail']['name_big']= "big_".$this->data['Image']['name'];
						    $this->data['Thumbnail']['path_big'] = "thumbnails/big_".$this->data['Image']['name'];
						    
						    $this->data['Thumbnail']['image_id']=  $this->Post->Image->id;	
						    $this->Post->Image->Thumbnail->save($this->data);
					    
					} 
				}
				}
				$this->Session->setFlash(sprintf(__('The %s has been saved', true), 'post'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(sprintf(__('The %s could not be saved. Please, try again.', true), 'post'));
			}
		}
	}
	
	function addf($id=null) {
		if (!empty($this->data)) {
			$this->Post->create();
			

			if ($post=$this->Post->save($this->data)) {
				//We get the coordinates with the address and we save a new point
				if (!empty($post)) {
					$this->data['Point']['post_id'] = $this->Post->id;
					App::import('Vendor', 'google_geo');
            		$googleGeo = new GoogleGeo($this->data["Post"]["address"]);
            		$geo = $googleGeo->geo();
            		$this->data['Point'] = array_merge($this->data['Point'],$geo); 
					$point=$this->Post->Point->save($this->data);
				}
				
				//We save a new picture that belongs to this post
				if (!empty($post)) {
					$upload=false;
					$url=$this->data["Image"]["photo_url"];
					$filename=WWW_ROOT."img/images/".$this->data["Image"]["photo_id"].".jpg";
					$file = fopen ($url, "rb");
					if (!$file) return false; else {
						$fc = fopen($filename, "wb");
						while (!feof ($file)) {
							$line = fread ($file, 1028);
							fwrite($fc,$line);
						}
						fclose($fc);
						$upload=true;	
					}
					//$result = $this->Uploader->uploadFiles('images', $this->data['Image']); 
					//if(array_key_exists('urls', $result)) {
					if($upload){  
						//$this->data['Image']['name']= str_replace(' ', '_',  $this->data['Image']['file']['name']);
					   	$this->data['Image']['name']= $this->data["Image"]["photo_id"].".jpg";
						
						//$this->data['Image']['path'] = $result['urls'][0];
						$this->data['Image']['path'] = "images/".$this->data["Image"]["photo_id"].".jpg";
						
					    $this->data['Image']['post_id']= $this->Post->id;
					    $image=$this->Post->Image->save($this->data);
					    
					    //And create the thumbnail for the GoogleMap
					    if (!empty($image)) {	
							App::import('Vendor', 'thumb', array('file' => 'phpthumb'.DS.'ThumbLib.inc.php'));
							$thumb = PhpThumbFactory::create(IMAGES. $this->data['Image']['path']);
							$thumb->adaptiveResize(40, 40);
							$thumb->save(IMAGES."thumbnails/small_".$this->data['Image']['name']);
							$this->data['Thumbnail']['name_small']= "small_".$this->data['Image']['name'];
						    $this->data['Thumbnail']['path_small'] = "thumbnails/small_".$this->data['Image']['name'];
						    
						    $thumb = PhpThumbFactory::create(IMAGES. $this->data['Image']['path']);
							$thumb->adaptiveResize(200, 200);
							$thumb->save(IMAGES."thumbnails/big_".$this->data['Image']['name']);
							$this->data['Thumbnail']['name_big']= "big_".$this->data['Image']['name'];
						    $this->data['Thumbnail']['path_big'] = "thumbnails/big_".$this->data['Image']['name'];
						    
						    $this->data['Thumbnail']['image_id']=  $this->Post->Image->id;	
						    $this->Post->Image->Thumbnail->save($this->data);
					    }
					} 
				
				}
				$this->Session->setFlash(sprintf(__('The %s has been saved', true), 'post'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(sprintf(__('The %s could not be saved. Please, try again.', true), 'post'));
			}
		}else{
			$this->set('photoid',$id);
		}
	}
	
	
	function myPosts($userId=null){
		$this->Post->recursive = 2;
		$this->set('myposts', $this->Post->find("all", array('conditions' => array('Post.fb_user_id' => $userId),'order' =>'Post.created DESC','limit' => 10 )));
	}

	function edit($id = null,$user_id=null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(sprintf(__('Invalid %s', true), 'post'));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($post=$this->Post->save($this->data)) {
				$this->Post->recursive = 2;
				$old = $this->Post->read(null, $id); 
				if (!empty($post)) {
					$this->data['Point']['id']=$old["Point"]["id"];
					$this->data['Point']['post_id'] = $this->Post->id;
					App::import('Vendor', 'google_geo');
            		$googleGeo = new GoogleGeo($this->data["Post"]["address"]);
            		$geo = $googleGeo->geo();
            		$this->data['Point'] = array_merge($this->data['Point'],$geo); 
					$point=$this->Post->Point->save($this->data);
				}
				
				//We save a new picture that belongs to this post
				if (!empty($post)) {
					if(!empty($this->data['Image']["file"]["name"])){
						if(isset($old['Image'][0]['Thumbnail']["path_small"])) unlink(WWW_ROOT."img".DS.$old['Image'][0]['Thumbnail']["path_small"]);
						if(isset($old['Image'][0]['Thumbnail']["path_big"])) unlink(WWW_ROOT."img".DS.$old['Image'][0]['Thumbnail']["path_big"]);
						if(isset($old['Image'][0]['path'])) unlink(WWW_ROOT."img".DS.$old['Image'][0]['path']);
						
						$this->data['Image']["id"]=$old['Image'][0]["id"];
						$result = $this->Uploader->uploadFiles('images', $this->data['Image']); 
						if(array_key_exists('urls', $result)) {  
							$this->data['Image']['name']= str_replace(' ', '_',  $this->data['Image']['file']['name']);
						    $this->data['Image']['path'] = $result['urls'][0];
						    $this->data['Image']['post_id']= $this->Post->id;
						    $image=$this->Post->Image->save($this->data);
						    
						    //And create the thumbnail for the GoogleMap
						    if (!empty($image)) {
						    	//$this->data['Image'][0]["Thumbnail"]["id"]=$old['Image'][0]["Thumbnail"]["id"];
						    	$this->data['Thumbnail']["id"]=$old['Image'][0]["Thumbnail"]["id"];
								App::import('Vendor', 'thumb', array('file' => 'phpthumb'.DS.'ThumbLib.inc.php'));
								$thumb = PhpThumbFactory::create(IMAGES. $this->data['Image']['path']);
								$thumb->adaptiveResize(40, 40);
								$thumb->save(IMAGES."thumbnails/small_".$this->data['Image']['name']);
								$this->data['Thumbnail']['name_small']= "small_".$this->data['Image']['name'];
							    $this->data['Thumbnail']['path_small'] = "thumbnails/small_".$this->data['Image']['name'];
							    
							    $thumb = PhpThumbFactory::create(IMAGES. $this->data['Image']['path']);
								$thumb->adaptiveResize(200, 200);
								$thumb->save(IMAGES."thumbnails/big_".$this->data['Image']['name']);
								$this->data['Thumbnail']['name_big']= "big_".$this->data['Image']['name'];
							    $this->data['Thumbnail']['path_big'] = "thumbnails/big_".$this->data['Image']['name'];
							    
							    $this->data['Thumbnail']['image_id']=  $this->Post->Image->id;	
							    $this->Post->Image->Thumbnail->save($this->data);
						    }
						}
					} 
				}
				if($user_id==null) $user_id=$this->data["Post"]["user_id"];
				$this->Session->setFlash(sprintf(__('The %s has been saved', true), 'post'));
				$this->redirect(array('action' => 'myposts',$user_id));
			} else {
				$this->Session->setFlash(sprintf(__('The %s could not be saved. Please, try again.', true), 'post'));
			}
		}
		if (empty($this->data)) {
			$this->Post->recursive = 2;
			$this->data = $this->Post->read(null, $id);
		}
	}
	
	function delete($id = null,$user_id=null) {
		if (!$id) {
			$this->Session->setFlash(sprintf(__('Invalid id for %s', true), 'post'));
			$this->redirect(array('action' => 'myposts',$user_id));
		}
		$this->Post->recursive = 2;
		$post = $this->Post->read(null, $id);
		if ($this->Post->delete($id)) {
			if(isset($post['Image'][0]['Thumbnail']["path_small"])) unlink(WWW_ROOT."img".DS.$post['Image'][0]['Thumbnail']["path_small"]);
			if(isset($post['Image'][0]['Thumbnail']["path_big"])) unlink(WWW_ROOT."img".DS.$post['Image'][0]['Thumbnail']["path_big"]);
			if(isset($post['Image'][0]['path'])) unlink(WWW_ROOT."img".DS.$post['Image'][0]['path']);	
			$this->Session->setFlash(sprintf(__('\'%s\' deleted', true), $post["Post"]["title"]));
			$this->redirect(array('action' => 'myposts',$user_id));
		}
		$this->Session->setFlash(sprintf(__('%s was not deleted', true), 'Post'));
		$this->redirect(array('action' => 'myposts',$user_id));
	}
	
	function addtoroute($post_id=null){
		if($post_id==null){
			$this->Session->setFlash("Invalid Post id");
			$this->redirect(array('action' => 'index'));
		}
		$post = $this->Post->read(null, $post_id);
		if(!empty($post)){
			if($this->Session->check("myroute")){
				$myroute = $this->Session->read('myroute');
				foreach($myroute as $postMy){
					if($postMy==$post_id){
						$this->Session->setFlash(sprintf(__('\'%s\' already exists your route', true), $post["Post"]["title"]));
						$this->redirect(array('action' => 'view',$post_id));
					}
				}
				$myroute=array_merge($myroute,array($post_id));
			}else{
				$myroute=array($post_id);
			}
			$this->Session->write('myroute', $myroute);
			$this->Session->setFlash(sprintf(__('\'%s\' was added to your route', true), $post["Post"]["title"]));
		}
		$this->redirect(array('action' => 'view',$post_id));
	}
	
	function myroute(){
		$this->Post->recursive = 2;
		if($this->Session->check("myroute")){
			$posts=array();
			$postsSaved=$this->Session->read('myroute');
			$i=0;
			foreach($postsSaved as $postSaved){
				$posts=array_merge($posts,array($i=>$this->Post->read(null, $postSaved)));
				$i++;
			}
			$this->set("posts",$posts);
		}else{
			$this->set("posts",null);
		}
	}
	
	function deleteRoute($id=null,$title){
		if($id!=null){
			if($this->Session->check("myroute")){
				$posts=$this->Session->read('myroute');
				$newPosts=array();
				foreach($posts as $post){
					if($post!=$id){
						$newPosts=array_merge($newPosts,array($post));
					}
				}
				$this->Session->write('myroute', $newPosts);
				$this->Session->setFlash(sprintf(__('\'%s\' was deleted from your route', true), $title));
				$this->redirect(array('action' => 'myroute'));
				
			}
		}
	}
	
	function printmy(){
		$this->layout="plain";
		$this->Post->recursive = 2;
		if($this->Session->check("myroute")){
			$posts=array();
			$postsSaved=$this->Session->read('myroute');
			$i=0;
			foreach($postsSaved as $postSaved){
				$posts=array_merge($posts,array($i=>$this->Post->read(null, $postSaved)));
				$i++;
			}
			$this->set("posts",$posts);
		}else{
			$this->set("posts",null);
		}
	}
	
	function getUsers(){
		return $this->Post->query("SELECT DISTINCT(fb_user_id) FROM posts");
	}
	
	function beforeFilter(){
		App::import('Helper', 'Facebook');
        $fb = new FacebookHelper();
        if(!$fb->isLoggedIn()){
        	$this->Session->setFlash("Please, log in with your Facebook account");
			$this->redirect(array('controller' => 'pages', 'action' => 'display', 'home'));
        }
	}
}
?>